package com.starblink.post.detail.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.ext.ApolloValSetExt
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.basic.route.RoutePage
import com.starblink.post.databinding.FragmentPostDetailBinding
import com.starblink.post.databinding.ItemPostDetailBinding
import com.starblink.post.detail.adapter.PostDetailHolder
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.fragment.ProductF

class PostDetailFragment(
    private val postId: String,
    private val traceId: String?,
    private val post: PostD? = null
) :
    BaseTVMFragment<FragmentPostDetailBinding, SinglePostDetailVM>() {

    companion object {
        fun newInstance(postId: String, traceId: String?, post: PostD?) =
            PostDetailFragment(postId, traceId, post)
    }

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.mList.value!!).apply {
            addVhDelegate {
                PostDetailHolder(
                    ItemPostDetailBinding.inflate(it.inflater, it, false),
                    requireActivity(), traceId, shareCallBack = {
                        viewModel.sharePost(postId)
                    }, this@PostDetailFragment.hashCode().toString(),viewModel.mList.value!!.size == 1
                )
            }
        }
    }

    override fun initData() {
        if (post != null) {
            var list = arrayListOf<PostD>()
            list.add(post)
            viewModel.mList.value = arrayListOf()
            viewModel.mList.value?.addAll(list)
            viewModel.mList.value = viewModel.mList.value
            viewBinding.rv.adapter = adapter

        } else {
            showStateLoading()
        }

        viewModel.getRecommend(postId)

        val layoutManager = LinearLayoutManager(context)
        viewBinding.rv.layoutManager = layoutManager

        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setEnableLoadMore(false)
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.getRecommend(postId)
            viewBinding.refresher.finishLoadMore(5000)
        }
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onCreate(owner: LifecycleOwner) {
                super.onCreate(owner)
                Log.i("PostDetailFragment", "1======onCreate===$postId ")
            }

            override fun onStart(owner: LifecycleOwner) {
                super.onStart(owner)
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
//                if (viewModel.mLoadActionLiveData.value?.action ?: null == LoadAction.STATE_ERROR) {
//                    mActivity.navigationTo(RoutePage.Post.PAGE_CONTENT_DELETED) {
//                        withString(
//                            RoutePage.Post.ARGS_TIP,
//                            viewModel.mLoadActionLiveData.value?.message
//                        )
//                    }
//                    mActivity.finish()
//                }
            }

            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
            }
        })

        syncMountedProductState()
    }

    /**
     * 同步挂载商品状态
     */
    private fun syncMountedProductState() {
        //同步挂载商品订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            for (index in viewModel.mList.value?.indices!!) {
                val post = viewModel.mList.value!![index]
                val productList = post.productList
                if (productList != null && productList.isNotEmpty()) {
                    for (item in productList) {
                        var it = item.productF
                        if (it.merchantWeb != null && it.merchantWeb!!.id == event.id && event.followed != it.merchantWeb!!.subOrNot) {
                            val merchant = it.merchantWeb!!
                            ApolloValSetExt.setApolloVal<ProductF.MerchantWeb>(
                                merchant,
                                "subOrNot",
                                event.followed
                            )
                            viewModel.mList.value!![index] = post
                            viewModel.mList.value = viewModel.mList.value
                            break
                        }
                    }
                }
            }
        }

        //同步挂载商品收藏状态
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            for (index in viewModel.mList.value?.indices!!) {
                val post = viewModel.mList.value!![index]
                val productList = post.productList
                if (productList != null && productList.isNotEmpty()) {
                    for (item in productList) {
                        var it = item.productF
                        if (it.id == event.id && event.collect != it.collected) {
                            ApolloValSetExt.setApolloVal<ProductF>(
                                it,
                                "collected",
                                event.collect
                            )
                            viewModel.mList.value!![index] = post
                            viewModel.mList.value = viewModel.mList.value
                            break
                        }
                    }
                }
            }
        }
    }

    override fun startObserve() {
        viewModel.mList.observe(this) {
            showStateSuccess()
            if (it.isNotEmpty()) {
                if (viewBinding.rv.adapter == null) {
                    viewBinding.rv.adapter = adapter
                }
                adapter.notifyDataSetChanged()
                if (viewBinding.refresher.isRefreshing) {
                    viewBinding.refresher.finishRefresh()
                }
                if (viewBinding.refresher.isLoading) {
                    viewBinding.refresher.finishLoadMore()
                }
                if (it.size > 1) {
                    viewBinding.refresher.setEnableLoadMore(true)
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            if (it.action == LoadAction.STATE_ERROR && it.message?.contains("has been deleted") == true) {
                mActivity.navigationTo(RoutePage.Post.PAGE_CONTENT_DELETED) {
                    withString(
                        RoutePage.Post.ARGS_TIP,
                        it.message
                    )
                }
                mActivity.finish()
            }
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentPostDetailBinding {
        return FragmentPostDetailBinding.inflate(inflater, container, false)
    }

    private var isViewCreated = false//布局是否被创建
    private var isLoadData = false//数据是否加载
    private var isFirstVisible = true//是否第一次可见

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isViewCreated = true
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        if (isFragmentVisible(this) && this.isAdded) {

            if (parentFragment == null || isFragmentVisible(parentFragment)) {
                onLazyInitData()
                isLoadData = true
                if (isFirstVisible) isFirstVisible = false
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isFragmentVisible(this) && !isLoadData && isViewCreated && this.isAdded) {
            onLazyInitData()
            isLoadData = true
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        //onHiddenChanged调用在Resumed之前，所以此时可能fragment被add, 但还没resumed
        if (!hidden && !this.isResumed)
            return
        //使用hide和show时，fragment的所有生命周期方法都不会调用，除了onHiddenChanged（）
        if (!hidden && isFirstVisible && this.isAdded) {
            onLazyInitData()
            isFirstVisible = false
        }
    }

    /**
     * 当前Fragment是否对用户是否可见
     * @param fragment 要判断的fragment
     * @return true表示对用户可见
     */
    private fun isFragmentVisible(fragment: Fragment?): Boolean {
        return !fragment?.isHidden!! && fragment.userVisibleHint
    }

    override fun onDestroy() {
        super.onDestroy()

        isViewCreated = false
        isLoadData = false
        isFirstVisible = true
    }

    fun onLazyInitData() {
        viewModel.getPostDetail(postId)
    }

}